
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:http/http.dart' as HTTP;
import 'http_config.dart';


// dio库的封装
class HttpRequest {
  static final BaseOptions options = BaseOptions(connectTimeout: HttpConfig.timeout, baseUrl: HttpConfig.baseUrl);
  static final Dio dio = Dio(options);

  static Future<T> request<T>(String url, {String method = 'get', Map<String, dynamic> params, Interceptor interceptor}) async {
    // 1、请求的单独配置
    final options = Options(method: method);

    // 2、添加一个拦截器
    Interceptor dInterceptor = InterceptorsWrapper(
      onRequest: (RequestOptions options) {
        // 1、在进行任何网络请求的时候，可以添加一个loading显示

        // 2、很多页面的访问必须要求携带Token，那么就可以在这里判断是有Token

        // 3、对参数进行一些处理，比如序列化处理等
        print("拦截了请求");
        return options;
      },

      onResponse: (Response response){
        print("拦截了响应");
        return response;
      },

      onError: (DioError error) {
        print("拦截了错误");
        return error;
      },
    );

    List <Interceptor>inters = [dInterceptor];

    dio.interceptors.addAll(inters);

    // 3、发送网络请求
    try {
      Response response = await dio.request<T>(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch(error) {
      return Future.error(error);
    }

  }


}









// 网络请求常见的三种方式 httpClient http库 dio库

// httpClient
void httpNetWorkDemo() async {

  // 1、创建client
  final httpClient = HttpClient();

  // 2、构造Uri
  final uri = Uri.parse("http://127.0.0.1/demo.json");

  // 3、发起请求、等待请求 同时您也可以配置请求headers body
  final request = await httpClient.getUrl(uri);

  // 4、关闭请求，等待响应
  final response = await request.close();
  // 5、解码响应的内容
  if (response.statusCode == HttpStatus.ok) {
    print(response.transform(utf8.decoder).join());
  } else {
    print(response.statusCode);
  }

}


// http库
void httpNetWork () async {
  final client = HTTP.Client();

  final url = Uri.parse("http://127.0.0.1/demo.json");

  final response = await client.get(url);

  if (response.statusCode == HttpStatus.ok) {
    print(response.body);
  } else {
    print(response.statusCode);
  }
}

// dio
void dioNetWork() async {
  // 1、创建Dio请求对象
  final dio = Dio();
  // 2、发送网络请求
  final response = await dio.get("http://127.0.0.1/demo.json");
  // 3、打印请求结果
  if (response.statusCode == HttpStatus.ok) {
    print(response.data);
  } else {
    print("请求失败：${response.statusCode}");
  }

}

